//编写store
import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
const foodStore = createSlice({
    name: 'foods',
    initialState: {
        //商品列表
        foodsList: [],
        //菜单激活下标值
        actionIndex: 0,
        cartList: []
    },
    reducers: {
        //更改商品列表
        setFoodList(state, action) {
            state.foodsList = action.payload
        },
        //更改菜单激活下标值
        changeActionIndex(state, action) {
            state.actionIndex = action.payload
        },
        //添加购物车
        addCart(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        //增count
        increCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            }
        },
        //减count
        decreCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count--
                if (item.count <= 0) {
                    state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
                }
            }
        },
        //清空购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})
const { setFoodList, changeActionIndex, addCart, increCount, decreCount, clearCart } = foodStore.actions
//异步代码编写
const fecthFoodList = () => {
    return async (dispatch) => {
        //编写异步请求
        //使用axios发送请求
        const res = await axios.get('http://localhost:3004/takeaway')
        //将请求到的数据存储到redux中
        //调用setFoodList方法
        dispatch(setFoodList(res.data))
    }
}

export { fecthFoodList, changeActionIndex, addCart, increCount, decreCount, clearCart }

const reducers = foodStore.reducer

export default reducers